package com.zm.daimai.damaiother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zm.daimai.damaiother.mapper.DmProductMapper;
import com.zm.damai.entity.DmProduct;
import com.zm.damaicommon.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 大麦商城-商品表-73 前端控制器
 * </p>
 *
 * @author lpt
 * @since 2024-09-08
 */
@RestController
@RequestMapping("/dmProduct")
public class DmProductController {

    @Autowired
    DmProductMapper productMapper;

    @RequestMapping("getProductInfo")
    DmProduct getProductById(@RequestParam int id){
        return productMapper.selectById(id);
    }

    @RequestMapping("querySecKillProduct")
    @Transactional
    public List<DmProduct> querySecKillProduct(){
        LambdaQueryWrapper<DmProduct> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(DmProduct::getStore);
        Page<DmProduct> page = new PageDTO<>(1, 10);
        page = productMapper.selectPage(page, lqw);
        //扣减1000个商品作为秒杀商品
        for (DmProduct product : page.getRecords()) {
            //扣减库存1000，保存到数据库
            product.setStore(product.getStore()-1000);
            productMapper.updateById(product);
            //设置秒杀商品库存为一千
            product.setStore(1000);
        }
        System.out.println("page.getRecords() = " + page.getRecords().size());
        System.out.println( page.getRecords());
        return page.getRecords();
    }

    @RequestMapping("updateSeckillProduct")
    Result updateSeckillProduct(@RequestBody List<DmProduct> productList){
        for (DmProduct product : productList) {
            DmProduct dmProduct = productMapper.selectById(product.getId());
            dmProduct.setStore(dmProduct.getStore() + product.getStore());
            productMapper.updateById(dmProduct);
            //TODO 优化方案
        }
        return new Result(1,"秒杀商品数量恢复完成",null);
    }

}

